<template>
  <div class="dynamic-box">
    <div class="dynamic" @scroll="handleScroll">
      <div class="left">
        <div class="person-simple-info">
          <el-card style="max-width: 300px">
            <div class="base-info">
              <a :href="'/space/home/'+userInfo.userId" target="_blank">
                <el-avatar :src="userInfo.userAvatar" :size="48"></el-avatar>
              </a>

              <div class="nickname">
                <a :href="'/space/home/'+userInfo.userId" target="_blank">
                  {{ userInfo.nickname }}
                </a>
              </div>

            </div>
            <div class="statistics">
              <div class="follow-count">
                <div class="number"><a @click="toCareList()">{{userStat.followCount}}</a></div>
                <div class="text"><a @click="toCareList()">关注</a></div>
              </div>
              <div class="fans-count">
                <div class="number"><a @click="toFansList()">{{userStat.fansCount}}</a></div>
                <div class="text"><a @click="toFansList()">粉丝</a></div>
              </div>
              <div class="dynamic-count">
                <div class="number"><a @click="toDynamics()">{{userStat.dynamicCount}}</a></div>
                <div class="text"><a @click="toDynamics()">动态</a></div>
              </div>
            </div>
          </el-card>
        </div>
        <div class="attention-dynamic-list">
          <el-card style="max-width: 300px">
            <div class="box">
              <div class="title"><h3>关注动态</h3><span class="text">{{concernList.length-1}}</span></div>
              <div class="more-attention">
              <span class="text">更多关注&nbsp;&nbsp;
                <el-icon><ArrowRight/></el-icon>
              </span>
              </div>
            </div>
            <div class="attention-dynamic-ul">
              <div class="list-item" @click="showDynamicList(item.userId)" v-for="item in concernList" :key="item.userId">
                <div class="list-item-left">
                  <el-avatar  :src="item.userAvatar" :size="48"></el-avatar>
                </div>
                <div class="list-item-right">
                  <div class="nickname">{{ item.nickname }}</div>
                  <div class="simple-introduction">{{ item.personalSignature }}</div>
                </div>
              </div>
<!--              <div class="list-item">-->
<!--                <div class="list-item-left">-->
<!--                  <el-avatar src="/img/avatar2.webp" :size="48"></el-avatar>-->
<!--                </div>-->
<!--                <div class="list-item-right">-->
<!--                  <div class="nickname">马士兵教育</div>-->
<!--                  <div class="simple-introduction">程序员职业规划指南</div>-->
<!--                </div>-->
<!--              </div>-->
<!--              <div class="list-item">-->
<!--                <div class="list-item-left">-->
<!--                  <el-avatar src="/img/avatar2.webp" :size="48"></el-avatar>-->
<!--                </div>-->
<!--                <div class="list-item-right">-->
<!--                  <div class="nickname">马士兵教育</div>-->
<!--                  <div class="simple-introduction">程序员职业规划指南</div>-->
<!--                </div>-->
<!--              </div>-->
            </div>
          </el-card>
        </div>
      </div>
      <div class="right">
        <el-card>
          <div class="publish-dynamic">
            <div class="input">
              <input class="ipt-text" type="text" v-model="form.contentTitle" placeholder="好的标题更容易获得支持">
              <br>
              <textarea v-model="form.contentText" class="input-text" cols="50" placeholder="有什么想和大家分享的?"></textarea>
            </div>

            <el-upload v-if="uploadAction" action="#"
                       :http-request="handleImgUpload"
                       list-type="picture-card">
              <el-icon><Plus /></el-icon>

              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>

          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
                </div>
              </template>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>


            <div class="submit">
              <div class="submit-left">
                <el-icon class="click-active" @click="uploadAction = !uploadAction"><PictureFilled /></el-icon>
                &nbsp;
                <span class="click-active">@</span>
              </div>
              <div class="dynamic-setting">
                <el-icon :size="25"><Setting /></el-icon>
              </div>
              <div class="submit-right">
                <el-button type="primary" @click="submitForm">发布</el-button>
              </div>
            </div>
          </div>
        </el-card>
        <el-card>
          <div class="nav">
            <div class="nav-item" @click="getAllDynamic()">全部</div>
            <div class="nav-item">视频投稿</div>
          </div>
        </el-card>
        <!--      <div class="dynamic-list" v-infinite-scroll="load" :infinite-scroll-disabled="disable">-->
        <div class="dynamic-list"  >

          <div class="dynamic-list-item" v-for="(item,index) in dynamicList" :key="item.dynamicId">
            <div class="my-card">
              <div class="item-box">
                <div class="item-left">
                  <a :href="'/space/home/'+item.publisherId" target="_blank">
                    <el-avatar class="pointer-show" :src="item.publisherAvatar" :size="50"></el-avatar>
                  </a>

                </div>
                <div class="item-right">
                  <div class="up-nickname">
                    <a :href="'/space/home/'+item.publisherId" target="_blank">
                      {{ item.publisherName }}
                    </a>
                  </div>
                  <div class="publish-time">
                    {{ item.createTime }}
                  </div>
                  <div class="publish-content" @click="toDynamicDetail(item.dynamicId)" v-if="item.forwardType === 0">
                    <div class="publish-content-title">
                      {{item.contentTitle}}
                    </div>
                    <div class="publish-content-text">
                      {{item.contentText}}
                    </div>
                    <template v-if="item.contentImg instanceof Array">
                      <img class="content-pic" v-for="(itemImg,index) in item.contentImg" :key="index" :src="itemImg" alt="" width="200">
                    </template>
                    <template v-else>
                      <img class="content-pic" :src="item.contentImg" alt="" width="150">
                    </template>
                  </div>
                  <div class="publish-content" @click="toDynamicDetail(item.dynamicId)" v-else-if="item.forwardType === 2">
                    <div class="publish-content-text">
                      {{item.contentText}}
                    </div>
                    <ForwardDynamicContent :data="item.forwardDynamicVO"></ForwardDynamicContent>
                  </div>
                  <div class="publish-content" @click="toDynamicDetail(item.dynamicId)" v-else-if="item.forwardType === 1 || item.forwardType === 3">
                    <template v-if="item.forwardVideoVO">
                      <div class="publish-content-text">
                        {{item.contentText}}
                      </div>
                      <div class="forward-box">
                        <div class="forward-content">
                          <div class="share-box">
                            <div class="share-header">
                              <a :href="'/space/home/'+item.forwardVideoVO.userId" target="_blank">
                                <el-avatar :src="item.forwardVideoVO.userAvatar" :size="30"></el-avatar>&nbsp;
                              </a>
                              <a :href="'/space/home/'+item.forwardVideoVO.userId" target="_blank">
                                <span class="nickname">{{item.forwardVideoVO.nickname}}</span>
                              </a>&nbsp;
                              的投稿视频
                            </div>
                            <div class="share-content">
                              <div class="content-left">
                                <a :href="'/video?videoId='+item.forwardVideoVO.videoId"  target="_blank">
                                  <el-image :src="item.forwardVideoVO.videoCover" style="width: 260px;height: 150px;overflow: hidden;border-radius: 5px;" fit="cover"></el-image>
                                </a>
                              </div>
                              <div class="content-right">
                                <a :href="'/video?videoId='+item.forwardVideoVO.videoId" target="_blank">
                                  <div>{{item.forwardVideoVO.videoTitle}}</div>
                                  <div>{{item.forwardVideoVO.videoIntroduction}}</div>
                                </a>
                                <div class="bottom-info">
                                  <el-icon><VideoPlay /></el-icon> &nbsp;{{item.forwardVideoVO.playCount}} &nbsp;&nbsp;
                                  <el-icon><ChatLineSquare /></el-icon>&nbsp;{{item.forwardVideoVO.videoBarrageCount}}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </template>
                    <template v-else>
                      原视频已删除
                    </template>
                  </div>
                </div>
              </div>
              <div class="item-action">
                <div class="action-item" >
                  <el-icon @click="forward(index)"><Share /></el-icon>
                  {{item.forwardCount === 0 ? '转发': item.forwardCount }}
                </div>
                <div class="action-item" @click="item.showComment = !item.showComment">
                  <el-icon><ChatRound /></el-icon>
                  {{item.commentCount === 0 ? '评论': item.commentCount }}
                </div>
                <div class="action-item" @click="doLike(item.dynamicId,item.publisherId, item)">
<!--                  <Icon icon="solar:like-broken" width="20" height="20" />-->
                  <img src="/icon/no-like-icon.webp" v-if="!item.userLikeStatus" alt="" width="20">
                  <img src="/icon/has-like-icon.webp" v-else alt="" width="20">
                  {{item.likeCount === 0 ? '点赞': item.likeCount }}
                </div>
              </div>
              <div class="item-forward" v-if="showForward && curForward === index">
                <div class="forward-left">
                  <el-avatar :src="userInfo.userAvatar" :size="30"></el-avatar>
                </div>
                <div class="forward-right">
                  <el-input
                      v-model="forwardForm.forwardDesc"
                      style="width: 650px"
                      :rows="2"
                      type="textarea"
                      placeholder="请自觉遵守互联网相关的政策法规，严禁发布色情，暴力，反动的言论。"
                  />
                  <el-button style="width: 50px" @click="handleForward(item)" type="primary">转发</el-button>
                </div>
              </div>
              <comment-list v-if="item.showComment" :dynamic-id="item.dynamicId"></comment-list>
            </div>
          </div>
          <div class="my-card">
            <el-empty v-if="isEmpty" description="没有更多动态了" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import {onMounted, reactive, ref} from "vue";
/* 上传图片相关 */
import {
  ArrowRight,
  ChatLineSquare,
  ChatRound,
  Delete,
  PictureFilled,
  Plus,
  Setting,
  Share,
  VideoPlay,
  ZoomIn
} from '@element-plus/icons-vue'
import http from "@/api/http.js";
import {ElMessage} from "element-plus";
import {
  forwardDynamic,
  getAllCaredUser,
  getDynamicList,
  getUserInfo,
  getUserStat,
  likeDynamic,
  publishDynamic
} from "@/api/api.js";
import {uploadDynamicImgUrl} from "@/constant/url.js";
import CommentList from "@/components/CommentList.vue";
import emitter from "@/utils/emitter.js";

import {useRouter} from "vue-router";
import {useUserStore} from "@/stores/userInfoStore.js";
import ForwardDynamicContent from "@/components/ForwardDynamicContent.vue";

const userStore = useUserStore();
const form = reactive({
  contentTitle:'',
  contentText:'',
  contentImg:''
})


const concernList = ref([]) // 关注列表
const pageParams = {
  page:1,
  pageSize:12
}
/* 获取所有用户(dev) */
onMounted(async ()=> {
  // 获取关注列表 ，限制12个
  const res = await getAllCaredUser(pageParams.page,pageParams.pageSize)
  console.log(res)
  concernList.value = res.data.records
})

const showDynamicList = async (userId) => {
  console.log(userId+"被选中了")
  dynamicList.value = []
  currentSelectedUserId.value = userId
  hasMore.value = true
  params.page = 1
  await loadMore()
}



/* 获取关注用户 */


const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

const handleRemove = (file) => {
  console.log(file)
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 图片上传
const uploadAction = ref(false)
const handleImgUpload = async ({file}) => {
  console.log(file)
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await http.post(uploadDynamicImgUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'authentication': `${localStorage.getItem('token')}`
      }
    })
    ElMessage.success('图片上传成功')
    form.contentImg = form.contentImg + res.data+","
  } catch (err) {
    ElMessage.error('图片上传失败')
    console.error('Upload error:', err)
  }
}
// 提交表单
const submitForm = async () => {
  // form.contentImg = uploadRes.data
  const res = await publishDynamic(form)
  console.log(res)
  if(res.code === 200){
    ElMessage.success("动态发布成功")
  }
}


const dynamicList = ref([])
const params = reactive({
  page: 1,
  pageSize: 5,
})
/* 获取动态 */

// 获取全部动态
const getAllDynamic = async () => {
  currentSelectedUserId.value = -1
  params.page = 1
  replace.value = true
  hasMore.value = true
  await loadMore();
}

const currentSelectedUserId = ref()
const replace = ref(true)  // 是否替换，比如动态列表切换为其他用户
const isEmpty = ref(false)
const loadMore = async () => {

  isEmpty.value = false
  if(isLoading.value || !hasMore.value) return;
  isLoading.value = true

  try {

    if(currentSelectedUserId.value){ // 查看是否查看所有动态
      params["userId"] = currentSelectedUserId.value
    }

    // 调用 API 获取数据（API 支持分页参数）
    const res = await getDynamicList(params);
    console.log(res)
    console.log("剩余数据长度")
    console.log(res.data.records.length)
    if (res.data.records.length === 0) {
      hasMore.value = false; // 没有更多数据
      isEmpty.value = true
      return;
    }
    // 处理返回的图片
    res.data.records.forEach((ele)=>{
      if(ele.contentImg && ele.contentImg.includes(",")){
        const arr = ele.contentImg.split(",")
        arr.pop()
        console.log(arr)
        ele.contentImg = arr
      }
      if(ele.forwardType === 2){
        if(ele.forwardDynamicVO.contentImg && ele.forwardDynamicVO.contentImg.includes(",")){
          const arr1 = ele.forwardDynamicVO.contentImg.split(",")
          arr1.pop()
          console.log(arr1)
          ele.forwardDynamicVO.contentImg = arr1
        }
      }
      ele["showComment"] = false
    })
    if(replace.value){
      dynamicList.value = res.data.records
    }else {
      dynamicList.value = [...dynamicList.value, ...res.data.records]; // 合并新旧数据
    }
    params.page++;
  } catch (err) {
    console.error('加载失败:', err);
  } finally {
    isLoading.value = false;
  }

}
const userInfo = ref({
  userId: 0,
  userAvatar: "",
  nickname: "",
})

const userStat = ref({
  followCount:0,
  fansCount:0,
  dynamicCount:0
})

onMounted(async ()=>{
  emitter.emit("isMessagePage",true)
  userInfo.value = userStore.userInfo;
  console.log(userInfo.value)
  let res = await getUserStat(userInfo.value.userId);
  console.log("统计信息结果为：")
  console.log(res)
  userStat.value = res.data
  await loadMore()

})


const isLoading = ref(false) // 是否正在加载
const hasMore = ref(true)// 是否还有更多数据


const handleScroll = (e) => {
  const container = e.target;
  // 滚动到底部条件：容器高度 + 滚动距离 >= 总内容高度 - 阈值（如 100px）
  const isBottom =
      container.scrollHeight - container.scrollTop <=
      container.clientHeight + 100;
  if (isBottom && !isLoading.value && hasMore.value) {
    replace.value = false
    loadMore();
  }
}

const router = useRouter();

const forwardForm = reactive({
  forwardDesc: "",
  forwardContentId: 0,
  forwardType:0
})
const showForward = ref(false)
const curForward = ref(0)
const forward = (index) => {
  curForward.value = index
  showForward.value = !showForward.value
}
const handleForward = async (item) => {
  let contentId = -1
  const {forwardType} = item
  if(forwardType === 0){
    contentId = item.dynamicId
  }
  if(forwardType === 1 || forwardType === 3){
    contentId = item.forwardVideoVO.videoId
  }
  if(forwardType === 2){
    contentId = item.forwardDynamicVO.dynamicId
  }
  // item.forwardType === 0?item.contentId:item.forwardType === 1?
  //     item.forwardVideoVO.videoId:item.forwardDynamicVO.contentId
  try {
    console.log(contentId)
    forwardForm.forwardContentId = contentId
    forwardForm.forwardType = forwardType
    const res = await forwardDynamic(forwardForm)
    console.log(res.data)
    await reload()
    ElMessage.success("转发成功")

  }catch (e){
    ElMessage.error("转发失败："+e)
  }
}

const reload = async () => {
  params.pageSize = params.page * params.pageSize
  params.page = 1
  replace.value = true
  hasMore.value = true
  await loadMore()
}


/* 点赞 */



const likeForm = {
  supporterId: 0,
  likeContentId:0,
  contentOwnerId:0
}
const doLike = async (dynamicId, ownerId,item) => {
  likeForm.likeContentId = dynamicId
  likeForm.contentOwnerId = ownerId
  likeForm.supporterId = userStore.userInfo.userId
  const res = await likeDynamic(likeForm);
  console.log(res)
  if(res.code === 200){
    if(res.msg.includes("取消")){
      ElMessage.success(res.msg);
      item.userLikeStatus = 0;
      item.likeCount --
      return;
    }
    item.userLikeStatus = 1;
    item.likeCount ++
    ElMessage.success("点赞成功！")
  }
}
/* 点赞结束 */

const toCareList = () => {
  window.open('/space/home/12',"blank")
}
const toDynamics = () => {
  const id = localStorage.getItem("userId")
  window.open('/space/dynamic/'+id,"blank")
}
const toFansList = () => {
  const id = localStorage.getItem("userId")
  window.open('/space/relation/'+id+'/fans',"blank")
}

const toDynamicDetail = (dynamicId) => {
  window.open('/d-detail/'+dynamicId,"blank")
}
</script>
<style scoped lang="scss">
.click-active{
  cursor: pointer;
}
.dynamic-box{
  width: 100%;
  background: url("/banner06.webp");
  .dynamic {
    box-sizing: border-box;
    height: 650px;
    overflow: auto;
    padding: 0 180px;
    display: flex;
    .left {
      box-sizing: border-box;
      margin-right: 15px;
      .person-simple-info {
        box-sizing: border-box;
        margin-bottom: 10px;
        .base-info {
          display: flex;
          height: 70px;
          .nickname {
            margin-left: 20px;
            height: 50px;
            line-height: 50px;
            font-weight: bold;
          }
        }
        .statistics{
          display: flex;
          .follow-count,.fans-count,.dynamic-count{
            cursor: pointer;
            width: 80px;
            height: 50px;
            text-align: center;
            .text{
              color:gray;
              font-size: 13px;
            }

          }
        }
      }

      .attention-dynamic-list {
        .box {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .title {
            display: flex;
            align-items: center;
            .text {
              margin-left: 5px;
              color: gray;
            }
          }

          .more-attention {
            color: gray;
            font-size: 13px;
          }
        }

        .attention-dynamic-ul {
          .list-item {
            height: 50px;
            display: flex;
            margin: 15px 0;
            cursor: pointer;
            .list-item-left {
              width: 60px;
            }
            .list-item-right {
              .nickname {
                font-size: 14px;
              }
              .simple-introduction {
                color: gray;
                font-size: 13px;
              }
            }
          }
        }
      }
    }
    .right{
      width: 800px;
      //background-color: #15dede;
      .publish-dynamic{
        .input{
          min-height: 100px;
          .ipt-text{
            outline: none;
            border: none;
          }
          .input-text{
            margin-top: 10px;
            outline: none;
            border: none;
            //max-height: 240px;
            resize: none; /* 禁止用户调整大小 */
            width: 100%; /* 设置宽度 */
            padding: 10px; /* 内边距 */
            font-family: Arial, sans-serif; /* 字体 */
            font-size: 16px; /* 字体大小 */
            line-height: 1.5; /* 行高 */
            background-color: #f9f9f9; /* 背景颜色 */
            border-radius: 5px; /* 圆角 */
            min-height: 10em; /* 最小高度为2行 */
            //max-height: 10em; /* 最大高度为7行 */
            overflow-y: auto; /* 超出最大高度时显示滚动条 */
            font-size: 14px;
          }

        }
        .submit{
          display: flex;
          .submit-left{
            height: 30px;
            line-height: 30px;
            font-size: 25px;
            width: 800px;
            //background-color: red;
          }
          .dynamic-setting{
            margin: 0 30px;
          }
        }

      }

      .nav{
        display: flex;
        .nav-item{
          cursor:pointer;
          color: gray;
          padding: 0 20px;
        }
      }
      .my-card{
        padding: 15px;
        border-radius: 2px;
        background-color: white;
        box-shadow: 0 0 10px 0 #bebebe;
        }
      .dynamic-list{

        .dynamic-list-item{

          margin: 10px 0;
          .my-card{
            padding: 15px;
            border-radius: 2px;
            background-color: white;
            box-shadow: 0 0 10px 0 #bebebe;
            .item-box{
              display: flex;
              .item-left{
                width: 80px;
                padding:0 15px;
              }
              .item-right{
                .up-nickname{
                  cursor: pointer;
                  height: 30px;
                  font-size: 19px;
                  color:deeppink;
                }
                .publish-time{
                  color: gray;
                  font-size: 13px;
                  height: 20px;
                  line-height: 20px;
                }
                .publish-content{
                  .content-pic{
                    border-radius: 5%;
                  }
                  .publish-content-text{
                    letter-spacing: 1px;
                    margin: 10px 0;
                  }
                  .publish-content-title{
                    letter-spacing: 1px;
                    margin: 5px 0 0;
                    color: #020202;
                    font-size: 16px;
                  }
                  .forward-box{

                    width: 680px;
                    //height: 30px;
                    box-sizing: border-box;
                    padding: 20px;
                    background-color: #eee7e7;
                    border-radius: 5px;
                    .forward-header{

                      display: flex;
                      justify-content: flex-start;
                      align-items: center;
                      height: 30px;
                      .source-nickname{
                        color: #ff008a;
                      }
                    }
                    .forward-content{

                      color: gray;
                      font-size: 13px;
                      .share-box{
                        width: 650px;
                        height: 200px;
                        background-color: #e7e7e7;
                        box-sizing: border-box;
                        padding: 10px;
                        .share-header{
                          .nickname{
                            font-size: 14px;
                            color:black;
                          }
                          display: flex;align-items: center;
                          //box-sizing: border-box;
                          //padding: 5px;
                          height: 40px;
                          font-size: 12px;
                          color: gray;
                        }
                        .share-content{

                          display: flex;color: black;
                          .content-right{
                            width:490px;
                            background-color: #f5f5f5;
                            display: flex;
                            flex-direction: column;
                            justify-content: space-between;
                            box-sizing: border-box;
                            padding: 10px 20px;
                            .bottom-info{
                              display: flex;
                              align-items: center;
                              font-size: 13px;
                              color: gray;
                            }
                          }
                        }
                      }
                    }
                  }
                }

              }
            }
            .item-action{
              margin-top: 15px;
              display: flex;
              padding-left: 80px;
              justify-content: space-between;
              .action-item{
                cursor: pointer;
              }
            }
            .item-forward{
              display: flex;
              margin-left: 80px;
              .forward-left{
                width: 40px;
                box-sizing: border-box;padding: 5px;

              }
              .forward-right{
                display: flex;
                flex-direction: column;
                align-items: flex-end;
              }
            }
          }
        }
      }
    }
  }
}

.pointer-show{
  cursor: pointer;
}
</style>